import React from 'react'
import { Icon as LegacyIcon } from '@ant-design/compatible'
import { Button, Dropdown, Menu, Layout } from 'antd'
import { Link, useLocation } from 'react-router-dom'
import { renderRoutes } from 'react-router-config'
import { rpc } from 'utils'
import menus from 'configs/menu'
import Login from './Login'

function renderMenus(menus) {
  return menus.map(v =>
    v.children ? (
      <Menu.SubMenu
        key={v.url}
        title={
          <span>
            <span>{v.name}</span>
          </span>
        }
      >
        {renderMenus(v.children)}
      </Menu.SubMenu>
    ) : (
      <Menu.Item key={v.url}>
        <Link to={v.url}>
          <span>{v.name}</span>
        </Link>
      </Menu.Item>
    )
  )
}

export default function Root(props) {
  const { route } = props
  const [defaultSelectedKeys, setDefaultSelectedKeys] = React.useState()
  const location = useLocation()

  React.useEffect(() => {
    const { pathname } = location
    const selected = menus.find(v => v.url === pathname)
    if (selected) setDefaultSelectedKeys([pathname])
  }, [])

  React.useEffect(() => {
    const fn = () => rpc.remote.screenLock()
    window.addEventListener('mousemove', fn)
    return () => {
      window.removeEventListener('mousemove', fn)
    }
  }, [])

  return (
    <Layout>
      {window === parent && (
        <>
          <Login />
          <Dropdown
            placement="topRight"
            trigger={['click']}
            overlay={
              <Menu selectable defaultSelectedKeys={defaultSelectedKeys}>
                {renderMenus(menus)}
              </Menu>
            }
          >
            <Button
              type="primary"
              size="large"
              shape="circle"
              icon={<LegacyIcon type="menu" />}
              style={{ position: 'fixed', bottom: 24, right: 24, zIndex: 999 }}
            />
          </Dropdown>
        </>
      )}
      <Layout.Content
        style={{
          // minHeight: haveIfream ? 'calc(100vh - 94px)' : '100vh',
          minHeight: '100vh',
        }}
      >
        {renderRoutes(route.routes)}
      </Layout.Content>
    </Layout>
  )
}
